
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.TimeZone;
import com.cmc.dao.TimeZoneDao;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class TimeZoneDaoHibernate extends BaseDaoHibernate implements TimeZoneDao {

    /**
     * @see com.cmc.dao.TimeZoneDao#getTimeZones(com.cmc.model.TimeZone)
     */
    public List getTimeZones(final TimeZone timeZone) {
        //return getHibernateTemplate().find("from TimeZone");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (timeZone == null) {
            return getHibernateTemplate().find("from TimeZone order by timeValue");
        } else {
            // filter on properties set in the timeZone
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(timeZone).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    Criteria criteria = session.createCriteria(TimeZone.class);
                    criteria.addOrder(Order.asc("timeValue"));
                    return criteria.add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.TimeZoneDao#getTimeZone(Long id)
     */
    public TimeZone getTimeZone(final Long id) {
        TimeZone timeZone = (TimeZone) getHibernateTemplate().get(TimeZone.class, id);
        if (timeZone == null) {
            log.warn("uh oh, timeZone with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(TimeZone.class, id);
        }

        return timeZone;
    }

    /**
     * @see com.cmc.dao.TimeZoneDao#saveTimeZone(TimeZone timeZone)
     */    
    public void saveTimeZone(final TimeZone timeZone) {
        getHibernateTemplate().saveOrUpdate(timeZone);
    }

    /**
     * @see com.cmc.dao.TimeZoneDao#removeTimeZone(Long id)
     */
    public void removeTimeZone(final Long id) {
        getHibernateTemplate().delete(getTimeZone(id));
    }
}
